<?php

namespace app\modules\api\controllers;
use Yii;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoom;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use app\modules\Product\models\Product;
use app\modules\Product\models\ProductRoom;
use app\modules\Order\models\OrderRoomCustomer;
use app\modules\Order\models\OrderRefund;
use app\modules\Order\models\OrderCustomer;
use app\modules\Order\models\OrderPriceType;
use app\modules\Order\models\OrderPrice;

/**
 * OrderController implements the CRUD actions for Order model.
 */
class OrderController extends Controller
{
    public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
//            'access' => [
//                'class' => AccessControl::className(),
//                'rules' => [
//                    [
//                        'allow' => true,
//                        'actions' => ['create','unrecovery','recovery','token','addroom','delroom'],
//                        'roles' => ['@'],
//                        //'matchCallback' => function ($rule, $action) {
//                        //	return  (Yii::$app->user->identity->username == 'admin') ? true : false;
//                        //}
//                    ],
//                    [
//                        'allow' => true,
//                        'actions' => ['neword','word','file-upload','del-img'],
//                        'roles' => ['?'],
//                    ],
//                ],
//            ],
        ];
    }


    // 取消订单
    public function actionUnrecovery(){

        $data = Yii::$app->request->get();
        if(!isset($data['token'])){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($data['token']);

        $id = $data['id'];
        if(empty($id)){
            return json_encode(['code'=>11,'message'=>'订单id不能为空']);
        }
        $model = $this->findModel($id);

        // 判断是否已被分团占用
        if(!empty($model->assign_id)){
            return json_encode(['code'=>12,'message'=>'订单已分团， 不能取消, 请先在团队中移除该订单']);
        }

        // 判断是否是关联订单
        if($model->isRelation > 1){
            return json_encode(['code'=>13,'message'=>'关联订单, 请先取消关联后操作']);
        }

        // 判断是否拼房
        if($model->merge_id){
            return json_encode(['code'=>14,'message'=>'该订单已拼房, 请先取消拼住的舱房']);
        }


        if($model->status == 1){	// 占位取消
            $model->status = 10;
        }elseif($model->status == 2){	// 定金取消
            $model->status = 13;
        }elseif($model->status == 3){	// 付款取消
            $model->status = 11;
        }elseif($model->status == 4){	// 提交取消
            $model->status = 12;
        }

        $model->save();

        // 更改订单所属舱房的状态
        OrderRoom::updateAll(['status'=>2], sprintf('order_id = %d', $id) );
        return json_encode(['code'=>1,'message'=>'取消订单成功']);
    }

    // 恢复已取消的订单
    public function actionRecovery(){

        $data = Yii::$app->request->get();
        if(!isset($data['token'])){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($data['token']);

        $id = $data['id'];

        if(empty($id)){
            return json_encode(['code'=>11,'message'=>'订单id不能为空']);
        }
        $model = $this->findModel($id); 	// ORDER MODEL

        if($model->status != 10){ // 占位取消的订单才容许恢复
            return json_encode(['code'=>12,'message'=>'占位取消的订单才允许恢复']);
        }

        // 判断库存数量是否足够
        $ret = Yii::$app->orderblock->isStock($model);
        // 只容许占位取消订单恢复
        if($ret){
            // 更改订单状态 判断当前订单属于何种状态 todo
            $model->status = 1;
            $model->save();

            // 更改订单所属舱房的状态
            OrderRoom::updateAll(['status'=>1], sprintf('order_id = %d', $id));
            return json_encode(['code'=>1,'id'=>$model->id,'order_code'=>$model->code,'message'=>'恢复订单成功']);
        }else{
            return json_encode(['code'=>13,'message'=>'库存余额不足']);
        }
    }

    public function actionCreate()
    {
        $data = Yii::$app->request->post('data');
        $token = Yii::$app->request->get('token');
//        $data = '{"Order":{"product_id":301,"member_id":1,"source":1,"is_merge":2,"remark":"\u5f20\u4e1c\u65ed\u5907\u6ce8\u4fe1\u606f","username":"\u5f20\u4e1c\u65ed","phone":"1510045506","company":"\u8fd9\u662f\u5f20\u4e1c\u65ed\u7684\u6d4b\u8bd5\u516c\u53f8"},"change_room":1,"change_room_num":2,"room":{"1":{"id":1,"num":5},"2":{"id":1,"num":6}}}';
//        $data = '{"Order":{"product_id":298,"member_id":1,"source":1,"is_merge":2,"remark":"\u5f20\u4e1c\u65ed\u5907\u6ce8\u4fe1\u606f","username":"\u5f20\u4e1c\u65ed","phone":"1510045506","company":"\u8fd9\u662f\u5f20\u4e1c\u65ed\u7684\u6d4b\u8bd5\u516c\u53f8"},"change_room":1,"change_room_num":2,"room":{"1":{"id":1,"num":5},"2":{"id":1,"num":6},"3":{"id":1,"num":6},"4":{"id":1,"num":6},"5":{"id":1,"num":6},"6":{"id":1,"num":6},"7":{"id":1,"num":6},"8":{"id":1,"num":6},"9":{"id":1,"num":6},"10":{"id":1,"num":6},"11":{"id":1,"num":6},"12":{"id":1,"num":6},"13":{"id":1,"num":6},"14":{"id":1,"num":6},"15":{"id":1,"num":6},"16":{"id":1,"num":6},"17":{"id":1,"num":6},"18":{"id":1,"num":6}}}';
//        $data = '{"Order":{"product_id":298,"member_id":1,"source":1,"is_merge":2,"remark":"\u5f20\u4e1c\u65ed\u5907\u6ce8\u4fe1\u606f","username":"\u5f20\u4e1c\u65ed","phone":"1510045506","company":"\u8fd9\u662f\u5f20\u4e1c\u65ed\u7684\u6d4b\u8bd5\u516c\u53f8"},"change_room":1,"change_room_num":2,"room":{"1":{"id":9226,"num":5},"2":{"id":9226,"num":6}}}';
//        $data = '{"product_id":298,"member_id":1,"source":1,"is_merge":2,"remark":"\u5f20\u4e1c\u65ed\u5907\u6ce8\u4fe1\u606f","username":"\u5f20\u4e1c\u65ed","phone":"1510045506","company":"\u8fd9\u662f\u5f20\u4e1c\u65ed\u7684\u6d4b\u8bd5\u516c\u53f8","room":{"1":{"id":9226,"num":5},"2":{"id":9226,"num":6}}}';
        $data = json_decode($data,true);
        if(!isset($token))
        {
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($token);

        if(empty($data['product_id'])){
            return json_encode(['code'=>11,'message'=>'团队id不能为空']);
        }
        $product = Product::findOne($data['product_id']);

        if($product->stock == 1){
            $model = new Order();
            $model->product_id = $data['product_id'];
            $model->member_id = $data['member_id'];
            $model->source = $data['source'];
            $model->is_merge = $data['is_merge'];
            $model->remark = $data['remark'];
            $model->username = $data['username'];
            $model->phone = $data['phone'];
            $model->company = $data['company'];
            $model->status = 1;
            $model->dentification = 1;
            if(isset($data['room']) && $model->save()){
                $code = $this->roomcreate($data, $model);
                return $code;
            }
        }else{
            return json_encode(['code'=>12,'message'=>'只支持标准库存格式添加.']);
        }

    }


    public function actionAddroom()
    {
//        $room = '{"room":{"1":{"id":9226,"num":2}}}';
//        $id = 1404;
//        $token = '93b59d07a6c57fc97b102bfb8fc';
        $id = Yii::$app->request->post('id');//订单id
        $room = Yii::$app->request->post('room');
        $token = Yii::$app->request->get('token');
        $data = json_decode($room,true);
        if(!isset($token)){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        if(empty($id)){
            return json_encode(['code'=>11,'message'=>'订单id不能为空']);
        }
        Yii::$app->token->tokenApi($token);

        $model = $this->findModel($id);

        $product = Product::findOne($model->product_id);

        if($product->stock == 1){
            $code = $this->roomcreate($data, $model ,2);
            Yii::$app->orderblock->order_status($model);

            return $code;
        }else {
            return json_encode(['code'=>12,'message'=>'只支持标准库存格式添加']);
        }
    }

    public function roomcreate($data, $order, $insert=1){
        $all = isset($data['room']) ? $data['room'] : NULL;
        if($all){
            $db = Yii::$app->db;

            $transaction = $db->beginTransaction();
            try{
                $price = 0;
                foreach($all as $room){
                    //  获取当前已售出库存数  // 判断库存是否足够
                    $productroom = ProductRoom::findOne($room['id']);
                    if($productroom->sell_out == 1) {
                        echo json_encode(['code'=>16,'message'=>'房间已经售罄']);
                        exit;
                    }
                    //已经预定出去的数量
                    $sell_num = OrderRoom::find()->where(['product_id'=>$order->product_id, 'room_id'=>$productroom->id, 'status'=>1, 'stock'=>1])->count();
                    // 新增订单 减少库存数
                    $model = new OrderRoom();
                    $model->product_id = $order->product_id;
                    $model->order_id = $order->id;
                    $model->room_id  = $room['id'];
                    $model->num      = $room['num'];
                    //总库存-1-已经预定的数量
                    $num = $productroom->num - 1 - $sell_num;

                    if($num < 0 ){
                        $transaction->rollBack();
                        // 新增情况 删除订单基础部分
                        if($insert == 1){
                            $order->delete();
                        }
                        echo json_encode(['code'=>13,'message'=>'订单舱房保存失败, 库存数不足']);
                        exit;
                    }

                    //设置价格
                    if($order->source == 1){  //直客价格
                        $price += ($productroom->price * $model->num);
                        $model->price = ($productroom->price * $model->num);
                    }elseif($order->source == 2){ // 同业价格
                        $price += ($productroom->inside_price * $model->num);
                        $model->price = ($productroom->inside_price * $model->num);
                    }

                    if(! $model->save()){
                        $transaction->rollBack();
                        echo json_encode(['code'=>14,'message'=>'订单舱房保存失败, 请重新添加.']);
                        exit;
                    }
                }
                $order->total_sale = $order->total_sale + $price;
                $order->price = $order->price + $price;
                $order->save();
                $transaction->commit();
                if($insert == 2){
                    echo json_encode(['code'=>1,'id'=>$order->id,'order_code'=>$order->code,'message'=>'添加舱房成功']);exit;
                }
                echo json_encode(['code'=>1,'id'=>$order->id,'order_code'=>$order->code,'message'=>'预订单创建成功']);
            }catch(\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }
    }

    public function actionDelroom()
    {
        $data = Yii::$app->request->get();
        if(empty($data['order_room_id'])){
            return json_encode(['code'=>11,'message'=>'订单舱房id不能为空']);
        }
        if(!isset($data['token'])){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }

        Yii::$app->token->tokenApi($data['token']);

        $model = $this->orderRoomModel($data['order_room_id']);

        $ret = OrderRoomCustomer::find()->where( ['order_id'=>$model->order_id, 'order_room_id'=>$model->id] )->all();

        if($ret){
            return json_encode(['code'=>12,'message'=>'请先取消舱房填写的入住人']);
        }

        if($model->merge_id){
            return json_encode(['code'=>13,'message'=>'请先取消拼住的舱房']);
        }

        if($model->delete()){
            // 记录退舱房申请记录
            $refund = new OrderRefund();
            $refund->product_id = $model->product_id;
            $refund->order_id = $model->order_id;
            $refund->order_room_id = $model->id;
            $refund->room_price = $model->price;  // 舱房的金额
            $refund->created_at = date("Y-m-d H:i:s");
            $refund->user_id    = Yii::$app->user->id;
            $refund->params =  json_encode($model->getAttributes());
            $refund->desc = $data['desc'];

            $order = Order::findOne($refund->order_id);
            if($model->order->status == 1){ // 占位订单  直接记录状态为占位直接取消 , 无需审批
                $refund->status = 3;

                $refund->price = 0; //	$model->price;
                $refund->examine_id = 93; // 操作人 记录为系统
                $refund->check_at = date("Y-m-d H:i:s");

                $p = $refund->room_price - $refund->price;	// 总金额 - 扣除金额  = 退还金额
                $p = ($p >= 0) ? $p : 0;

                $order->refund_price = ($order->refund_price + $refund->price); // 累加以前的扣除金额

                $order->total_sale = $order->total_sale - $p;  //  计算舱房金额
                // 重新计算订单金额
                //$total =  $order->price - $p;  // 实际金额  = 当前实际金额 - 退款金额  (舱房金额  - 已审批优惠  + 附加费)
                // 计算优惠金额	及 佣金金额  todo
                $price = $order->total_sale - $order->sale_price - $order->commiss;

                // 计算附加费金额
                if($order->priceSum){
                    $price = $price+$order->priceSum;
                }

                $price = ($price <=0) ? 0 : $price;
                $order->price = $price;

                //$order->price = ($total <0) ? 0 : $total;
                $ret = $order->save();
            }

            $ret = $refund->save();
            // 记录日志
            $name = $model->productRoom->room->name . '  ' . $model->productRoom->room->code ;
            Yii::$app->logs->info($order->id, 1, sprintf("取消舱房 %s", $name));

            // 变更订单状态
            Yii::$app->orderblock->order_status($order);

            return json_encode(['code'=>1,'message'=>'减仓成功']);



        }else{
            return json_encode(['code'=>14,'message'=>'减仓失败']);

        }




    }

    protected function orderRoomModel($id)
    {
        if (($model = OrderRoom::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }




    /**
     * @param integer $id
     * @return Order the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id){

        if (($model = Order::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }



    public function actionAddmember()
    {
//        $member =  array(
//                'order_id' => 1377,
//                'order_room_id' => 3593,
//                'first_name' => 'aa',
//                'en_first_name' => 'AA',
//                'last_name' => '是',
//                'en_last_name' => 'SHI',
//                'card' => 1212112,
//                'gender' => 2,
//                'birthday' => 1970-01-01,
//                'passport' => 'E00864747',
//                'native' => '北京',
//                'passport_add' => '北京',
//                'passport_grant' => 2011-11-11,
//                'passport_date' => 2021-11-10,
//                'country' => '中国',
//                'card_address' => '北京',
//                'nation' => '汉',
//                'phone' => 1111111,
//                'passport_type' => 3,
//                'passport_img' => '',
//                'card_img' =>''
//        );

//        print_r(json_encode($member));die;


        $member = Yii::$app->request->post('member');
        $token = Yii::$app->request->get('token');

//        $member = '{"order_id":1377,"order_room_id":3593,"first_name":"aa","en_first_name":"AA","last_name":"\u662f","en_last_name":"SHI","card":"1212112","gender":2,"birthday":"","passport":"E00864747","native":"\u5317\u4eac","passport_add":"\u5317\u4eac","passport_grant":"","passport_date":"","country":"\u4e2d\u56fd","card_address":"\u5317\u4eac","nation":"\u6c49","phone":"1111111","passport_type":3}';
//        $token = '93b59d07a6c57fc97b102bfb8fc';
        $data = json_decode($member,true);
        if(empty($data['order_id'])){
            return json_encode(['code'=>11,'message'=>'订单id不能为空']);
        }

        if(!isset($token)){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($token);

        $model = new OrderCustomer();
        $rc = new OrderRoomCustomer();
        $order = Order::findOne($data['order_id']);

        $model->order_id = $data['order_id'];     //订单id
        $model->first_name = $data['first_name'];    //姓氏
        $model->en_first_name = $data['en_first_name'];   //英文姓
        $model->last_name = $data['last_name'];   //名字
        $model->en_last_name = $data['en_last_name'];   // 名字拼音
        $model->card = $data['card'];   //身份证号
        $model->gender = $data['gender'];   //性别1男 2女
        $model->birthday = $data['birthday'];   //出生日期
        $model->passport = $data['passport'];   //护照号码
        $model->native = $data['native'];    //出生地
        $model->passport_add = $data['passport_add'];   //护照签发地
        $model->passport_grant = $data['passport_grant'];   //护照签发日期
        $model->passport_date = $data['passport_date'];    // 护照有效期
        $model->country = $data['country'];    //国籍
        $model->card_address = $data['card_address'];    //身份证签发地
        $model->nation = $data['nation'];    //名族
        $model->phone = $data['phone'];   //手机号码
        $model->passport_type = $data['passport_type'];   //护照类型 1原件 2复印件 3其他

        if ($model->save()){
            $customer_id = $model->id;
            $rc->order_id = $data['order_id'];
            $rc->order_room_id = $data['order_room_id'];
            $rc->customer_id = $customer_id;
            $rc->status = 1;
            $rc->price = $order->price;
            if($rc->save()){

                //必选附加费
                $orderPriceType = OrderPriceType::find()->where(['product_id'=>$order->product_id,'type'=>2])->all();
                if($orderPriceType){
                    foreach($orderPriceType as $opt){
                        $orderPrice = OrderPrice::find()->where(['type'=>$opt->id,'order_id'=>$order->id])->one();
                        if($orderPrice){
                            $orderPrice->num = $orderPrice->num+1;
                            $customers = json_decode($orderPrice->customers);
                            array_push($customers,$customer_id);
                            $orderPrice->customers = $customers;
                            $orderPrice->save();
                        }else{
                            $orderPrice = new OrderPrice();
                            $orderPrice->desc = $opt->desc;
                            $orderPrice->price = $opt->price;
                            $orderPrice->num = 1;
                            $orderPrice->order_id = $order->id;
                            $orderPrice->type = $opt->id;
                            $customers = [$customer_id];
                            $orderPrice->customers = $customers;
                            $orderPrice->save();
                        }
                    }

                }


                return json_encode(['code'=>1,'message'=>'添加成功']);
            }
        }else{
            return json_encode(['code'=>12,'message'=>'添加失败']);
        }


    }



    public function actionCustomers()
    {
        $order_id = Yii::$app->request->get('order_id');
        $token = Yii::$app->request->get('token');

        if(empty($order_id)){
            return json_encode(['code'=>12,'message'=>'订单id不能为空']);
        }

        if(!isset($token)){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($token);

        $customers = [];
        $all2 = OrderCustomer::find()->where(['order_id'=>$order_id, 'status'=>1])->all();
        if($all2){
            foreach($all2 as $c){
                //$customers[$c->id] = [$c->first_name . $c->last_name, $c->roomCustomer->order_room_id  ];
                if($c->roomCustomer){ // 该用户是否分配在房间内, 未分配在房间内的视为取消用户

                    $customers[$c->roomCustomer->order_room_id][$c->id] = $c->first_name . $c->last_name;
                }
            }
        }

        $data = [];
// 获取附加费类型
        $order = Order::findOne($order_id);
        $all = OrderPriceType::find()->where(['product_id'=>$order->product_id,'type'=>1])->all();
        if($all){
            //$data = yii\helpers\ArrayHelper::map($all, 'id', 'name');
            foreach($all as $da){
                $data[$da->id] = $da->name . ' / ' . Yii::$app->formatter->asCurrency($da->price);
            }
        }

        return json_encode(['code'=>1,'data'=>$data,'member'=>$customers,'message'=>'请求成功']);
    }


    public function actionAddprice()
    {
//        $data = array(
//            'order_id' => 1362,
//            'type' => 5,
//            'customers' => Array
//    (
//        '0' => 3734,
//                    '1' => 3735,
//                ),
//        );

        $obj = Yii::$app->request->post('data');

        $token = Yii::$app->request->get('token');
        $data = json_decode($obj,true);
        if(!isset($token)){
            return json_encode(['code'=>10,'message'=>'Token未设置']);
        }
        Yii::$app->token->tokenApi($token);

        if(empty($data['order_id'])){
            return json_encode(['code'=>11,'message'=>'订单id不能为空']);
        }

        $model = new OrderPrice();
        $model->order_id = $data['order_id'];
        $model->type = $data['type'];
        $model->customers = $data['customers'];
        if($model->save()){
            $order = Order::findOne($model->order_id);

            $code = $this->order_status($order);

            return $code;

        }else{
            return json_encode(['code'=>12,'message'=>'添加失败']);
        }




    }


    public function order_starus($order)
    {
        // 获取订单实收金额
        $finance_price = $order->financeSuccess;

        if($order->price <= $finance_price ){ // 付全款

            $order->status = 3;
        }elseif( ($order->price > $finance_price) && ($finance_price > 0) ){  // 定金

            $order->status = 2;
        }elseif($finance_price == 0){ // 未付款  占位

            $order->status = 1;
        }


        if($order->save()){
            return json_encode(['code'=>1,'message'=>'添加成功']);die;
        }

    }







}
